package com.hundsun.yr.universal.p2p.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.View;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.netstatus.NetUtils;
import com.hundsun.yr.universal.library.view.BrowserLayout;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseActivity;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import es.voghdev.pdfviewpager.library.VerticalPDFViewPager;
import es.voghdev.pdfviewpager.library.adapter.PDFPagerAdapter;
import es.voghdev.pdfviewpager.library.adapter.PdfScale;

/**
 * Created by xx on 2017/6/17.
 */
public class InvestProtocolActivity extends BaseActivity{
    private BrowserLayout bl_loading_pdf;
    private VerticalPDFViewPager verticalPDF_viewpager;
    private String filePath;
    private File file;
    private PDFPagerAdapter adapter;
    private String protocol_name;
    private String protocol_url = "invest_default";
    private static final int REQUEST_PERMISSION = 0;
    private HttpResponse httpResponse1;

    @Override
    protected boolean isApplyKitKatTranslucency() {
        return true;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_webview_pdf_test;
    }

    @Override
    protected void initViewsAndEvents() {
        toolbar_title.setText(protocol_name);
        verticalPDF_viewpager = findView(R.id.verticalPDF_viewpager);
        bl_loading_pdf = findView(R.id.bl_loading_pdf);
        filePath = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + protocol_url + "/investprotocol.pdf";
        file = new File(filePath);
        if (file.exists()){
            try{
                //在这里进行版本号的判断
                if (Build.VERSION.SDK_INT >= 21 ){
                    adapter = new PDFPagerAdapter.Builder(mContext).setPdfPath(filePath).setScale(getPdfScale()).create();
                    verticalPDF_viewpager.setAdapter(adapter);
                } else {
                    bl_loading_pdf.loadUrl(protocol_url);
                    return;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        } else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    downLoadFile(protocol_url);
                }
            }).start();
        }

    }


    protected void initImmersionBar() {
        super.initImmersionBar();
        mImmersionBar.titleBar(R.id.common_toolbar).init();
    }


    @Override
    protected void getBundleExtras(Bundle extras) {
        protocol_name = extras.getString("protocol_name");
        protocol_url = extras.getString("protocol_url");
    }

    @Override
    protected void onEveComming(EventCenter eventCenter) {

    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected View getLoadingTargetView() {
        return null;
    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {

    }

    @Override
    protected void onNetworkDisConnected() {

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return true;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }


    private void downLoadFile(String url) {
        HttpClient httpClient1 = new DefaultHttpClient();
        HttpGet httpGet1 = new HttpGet(
                url);
        try {
            httpResponse1 = httpClient1.execute(httpGet1);
            StatusLine statusLine = httpResponse1.getStatusLine();
            if (statusLine.getStatusCode() == 200) {
                loadFile(httpResponse1);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpClient1.getConnectionManager().shutdown();
        }
    }

    private void loadFile(HttpResponse httpResponse1) throws IOException {
        filePath = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/investprotocol.pdf";
        file = new File(filePath);
        FileOutputStream outputStream = new FileOutputStream(file);
        InputStream inputStream = httpResponse1.getEntity()
                .getContent();
        byte b[] = new byte[1024];
        int j = 0;
        while ((j = inputStream.read(b)) != -1) {
            mHandler.sendEmptyMessage(DOWN_JINDU);
            outputStream.write(b, 0, j);
        }
        mHandler.sendEmptyMessage(DOWN_OVER);
        outputStream.flush();
        outputStream.close();
    }

    private final int DOWN_JINDU = 0;
    private final int DOWN_OVER = 1;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_JINDU:
                    break;
                case DOWN_OVER:
                    try{
                        //在这里进行版本号的判断
                        if (Build.VERSION.SDK_INT >= 21){
                            adapter = new PDFPagerAdapter(mContext, filePath);
                            verticalPDF_viewpager.setAdapter(adapter);
                        } else {
                            bl_loading_pdf.loadUrl(protocol_url);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    break;
                default:
                    break;
            }
        }
    };

    private PdfScale getPdfScale() {
        PdfScale scale = new PdfScale();
//        scale.setScale(3.0f);
        scale.setCenterX(getScreenWidth(this) / 2);
        scale.setCenterY(getScreenHeight(this));
        return scale;
    }

    public int getScreenWidth(Context ctx) {
        int w = 0;
        if (ctx instanceof Activity) {
            DisplayMetrics displaymetrics = new DisplayMetrics();
            ((Activity) ctx).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
            w = displaymetrics.widthPixels;
        }
        return w;
    }

    public int getScreenHeight(Context ctx) {
        int h = 0;
        if (ctx instanceof Activity) {
            DisplayMetrics displaymetrics = new DisplayMetrics();
            ((Activity) ctx).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
            h = displaymetrics.heightPixels;
        }
        return h;
    }
}
